package com.lizardmind.haofudoctor.ui.main

import android.Manifest
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.View
import com.blankj.utilcode.util.EncodeUtils
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView
import com.linxiao.framework.activity.BaseSplashActivity
import com.linxiao.framework.dialog.AlertDialogManager
import com.linxiao.framework.glide.GlideModuleConfig
import com.linxiao.framework.net.cache.CacheManager
import com.linxiao.framework.permission.PermissionManager
import com.linxiao.framework.permission.RequestPermissionCallback
import com.linxiao.framework.util.AESUtils
import com.linxiao.framework.util.FileUtil
import com.linxiao.framework.util.getDataBinding
import com.linxiao.framework.util.ke
import com.lizardmind.haofudoctor.AppApplication
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.databinding.ActivitySplashBinding
import com.lizardmind.haofudoctor.manager.postApi
import com.lizardmind.haofudoctor.other.*
import com.lizardmind.haofudoctor.test.TestActivity
import com.luck.picture.lib.tools.PictureFileUtils
import io.reactivex.functions.Consumer
import io.rong.imkit.RongIM
import io.rong.imlib.model.Conversation
import org.bouncycastle.util.encoders.Base64
import org.bouncycastle.util.encoders.Hex
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.act
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.toast


class SplashActivity : BaseSplashActivity() {

    private val binding by lazy { getDataBinding<ActivitySplashBinding>(R.layout.activity_splash) }

    override fun onCreatRootView(): View = binding.root

    override fun onInitView(savedInstanceState: Bundle?) {
        setEvent(true)
        TwinklingRefreshLayout.setDefaultHeader(SinaRefreshView::class.java.name)
    }

    private var isFrist = true

    override fun onStart() {
        super.onStart()
        //检查是否有读写权限
        PermissionManager.performWithPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        ).doOnProhibited {
            //当该权限禁用的时候触发
            AlertDialogManager.createAlertDialogBuilder()
                    .setMessage("读写手机权限是非常重要的权限，请到权限管理去打开权限")
                    .setPositiveText("确定")
                    .setPositiveButton { _, _ ->
                        //调到设置页面让用户设置权限
                        applicationContext.startActivity(PermissionManager.getAppDetailSettingIntent(applicationContext))
                    }
                    .setNegativeText("取消")
                    .setNegativeButton { _, _ ->
                        //如果用户不给权限就关闭app，敢不给权限
                        finish()
                    }.show()
        }.perform(act,object : RequestPermissionCallback{
            //当能获取权限时触发
            override fun onGranted() {
                Config.getPK()
                if(isFrist){
                    isFrist = false
                    FileUtil.makeDirs(CacheManager.CACHE_PATH)
                    FileUtil.makeDirs(GlideModuleConfig.path)

                }
            }
            override fun onDenied() {}
        })
    }

    @Subscribe
    public fun getPK(event:PKEvent){
        Handler().postDelayed({
            if(event.seccess){
                //密钥获取成功
                //判断本地是否有token，如果有就登陆
                //如果没有就调到登陆界面
                if(DoctorInfo.token.isEmpty()){
                    startActivity(intentFor<LoginActivity>())
                    finish()
                }else{
                    //有token，调用登陆接口登陆
                    observe {
                        postApi<Request<DoctorBean>>(
                                hashMapOf("action" to "token_register","token" to DoctorInfo.token)
                                , Consumer {
                            it.dispose {
                                DoctorInfo.updataDoctor(it)
                                AppApplication.connect(it.rToken)
                            }
                        })
                    }
                }
            }
        }, 2000)
    }

    @Subscribe
    public fun getRongConnect(rc:RongConnectEvent){
        if(rc.status){
            toast("登陆成功")
//            startActivity(intentFor<MainActivity>())
            RongIM.getInstance().startSubConversationList(this, Conversation.ConversationType.PRIVATE)
        }else{
            toast("登陆失败")
        }
    }
}
